#!/bin/sh

usage() {
    cat <<EOF
Run code lints under development machine.

Usage:
    $0 <mode> [--fix]

Mode:
    go    Run golang lint utilities
    vue   Run vue lint utilities
    all   Run both golang and vue lints
EOF
    exit 1
}

go() {
    local fix=$1

    [ "$fix" = "true" ] && EXTRA_ARGS="--fix" || EXTRA_ARGS=""

    [ ! -e .golangci.yaml ] && echo "ERROR: Run the script from the project root." && exit 1

    for container in agent:docker agent:native api ssh cli; do
        echo "Running Golang linter on $container"

        case $container in
            ssh)
                EXTRA_ARGS="$EXTRA_ARGS --build-tags internal_api"
                ;;
            agent:docker)
                EXTRA_ARGS="$EXTRA_ARGS --build-tags docker"

                container=$(echo $container | cut -d':' -f 1)
                ;;
            agent:native)
                EXTRA_ARGS="$EXTRA_ARGS --build-tags native"

                container=$(echo $container | cut -d':' -f 1)
                ;;
        esac

        # Run golangci-lint on a running container
        docker-compose \
            -f docker-compose.yml -f docker-compose.dev.yml \
            exec $container golangci-lint run ./... $EXTRA_ARGS
    done

    echo "Running Golang linter on pkg"
    docker-compose \
	    -f docker-compose.yml -f docker-compose.dev.yml \
	    exec api sh -c "(cd ../pkg; golangci-lint run $EXTRA_ARGS ./... )"
}

vue() {
    local fix=$1

    [ ! -d ui ] && echo "ERROR: Run the script from the project root." && exit 1

    [ "$fix" = "true" ] && EXTRA_ARGS=" -- --fix" || EXTRA_ARGS=":no-fix"

    echo "Running UI lints"

    # Run linter on a running container
    docker-compose \
        -f docker-compose.yml -f docker-compose.dev.yml \
        exec ui npm run lint$EXTRA_ARGS
}

mode=$1
arg=$2

case "$arg" in
    "--fix")
        fix="true"
        ;;
esac

case "$mode" in
    "go")
        go $fix
        ;;
    "vue")
        vue $fix
        ;;
    "all")
        go $fix
        vue $fix
        ;;
    *)
        usage
        ;;
esac

